import com.alibaba.moco.RedisPoolInstance
import com.alibaba.moco.util.BaseTypeUtil
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import org.apache.commons.lang.StringUtils
import redis.clients.jedis.Jedis
import script.GlobalValues
import script.moco.dto.OrderInfo
import script.v1.didiCallback.NoticeCallback
import script.v1.didiCallback.PayNotifyRequest
/**
 * 模拟 滴滴 费用确认
 * Created by wb-lj240895 on 2016/11/1.
 */
def excute(request) {
    def slurper = new JsonSlurper()
    def params = request.getParameterMap();
    Jedis redis = RedisPoolInstance.getRedisClient()
    //欢行异常判断
    def e = redis.hget(GlobalValues.KEY_EXCEPTION,"feeConfirm")
    if (!StringUtils.isBlank(e)) {
        def eJson = slurper.parseText(e)
        return eJson
    }
    ConfirmRequest req = BaseTypeUtil.mapToBean(params, ConfirmRequest.class) as ConfirmRequest
    String token = req.getAccess_token()
    System.out.println(token)
    ConfirmResponse response = new ConfirmResponse()
    if (token != null/* && redis.exists(token)*/) {
        //TODO:判断订单是否存在 存在则更新订单信息

        def detailStr  = redis.get(GlobalValues.KEY_ORDER+req.getOrder_id() )
        def detailJson = slurper.parseText(detailStr)
        //生成随机价格
        // def fee = Double.valueOf(BaseTypeUtil.randomDoubleNum(200))

        NoticeCallback noticeCallbackTool = new NoticeCallback();
        String callbackUrl =  noticeCallbackTool.getCallbackUrlFromRequest(request, false);
        new Thread(new Runnable() {
            @Override
            void run() {
                Thread.sleep(3000);
                PayNotifyRequest payNotifyRequest = new PayNotifyRequest();

                System.out.println("detail:"+detailStr);
                def data = JsonOutput.toJson(detailJson)

                if (data.contains("order") ){
                    def orderMap = detailJson.get("order")
                    def order = BaseTypeUtil.jsonToBean(orderMap, OrderInfo.class) as OrderInfo
                    order.setStatus(700)
                    detailJson.putAt("order",order)
                }else{
                    System.out.println("OrderDetail data err ,can`t find property 'order'")
                }
                if ( data.contains("price") ){
                    def priceMap = detailJson.get("price")
                    def price = JsonOutput.toJson(priceMap)

                    if (price.contains("total_price")){
                        payNotifyRequest.setTotalPrice(new BigDecimal( priceMap.total_price).floatValue());
                        /*callbackDidiPayRequest.setTotalPrice(new BigDecimal( priceMap.total_price))*/
                    }
                }else{
                    System.out.println("OrderDetail data err ,can`t find property 'price'")
                }
                //支付回调


                payNotifyRequest.setOrderId(req.getOrder_id());
                def info = redis.get(GlobalValues.KEY_CALLBACK_INFO + req.getOrder_id());
                payNotifyRequest.setCallbackInfo(info);
                payNotifyRequest.setNormalDistance(20);
                payNotifyRequest.setStatus(700);

                if (StringUtils.isNotBlank(callbackUrl)) {
                    noticeCallbackTool.handPayNotify(callbackUrl, payNotifyRequest);

                }
                detailJson.order.status = 700
                redis.set(GlobalValues.KEY_ORDER+ req.getOrder_id(),JsonOutput.toJson(detailJson))
                redis.expire(GlobalValues.KEY_ORDER+ req.getOrder_id(),GlobalValues.RIDES_EXPIRE)
            }
        }).start();
        //
        /* OrderPriceDetail det = new OrderPriceDetail();
         System.out.println("设置费用详情")
         det.setAmount(String.valueOf(detailJson.price.total_price))
         det.setName("正常行驶费用\"或\"超出套餐部分行驶距离费")
         det.setType("normal_fee")
         System.out.println(detailJson.price.detail)

         detailJson.price.detail.add(det);
         redis.set(req.getOrder_id(), JsonOutput.toJson(detailJson).toString())*/


        response.setErrno(0)
        response.setErrmsg("SUCCESS")
        response.setData(new OrderId())
        response.getData().setOrder_id(req.getOrder_id())
        return JsonOutput.toJson(response)
    } else {
        response.setErrno(-1)
        response.setErrmsg("token错误")
        return JsonOutput.toJson(response)
    }
}

public class ConfirmRequest {
    String client_id  //  yes  申请应用时分配的AppKey
    String access_token  //  yes  授权后的access token
    String order_id  //  yes  要确认支付的订单号
    String timestamp  //  yes  当前时间戳
    String sign  //  yes  签名 详细算法参见 签
    // 名验证 章节
}

public class ConfirmResponse {
    int errno
    String errmsg
    OrderId data
}
public class OrderId {
    String  order_id
}